package cn.jekun.shop.common.service;

import java.math.BigDecimal;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpCart;
import cn.jekun.component.core.service.gen.ErpCartAttrService;
import cn.jekun.component.core.service.gen.ErpCartService;
import cn.jekun.component.core.service.gen.ErpMerchandiseService;
import cn.jekun.shop.web.bean.ErpCarts;

@Service(CartService.BEAN_NAME)
public class CartService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.common.service.CartService";
	@Override
	public String getNamespace() {
		return "SHOP_CART";
	}
	@Resource(name=ErpCartService.BEAN_NAME)
	ErpCartService cartService;
	@Resource(name=ErpMerchandiseService.BEAN_NAME)
	ErpMerchandiseService erpMerchandiseService;
	
	@Resource(name = ErpCartAttrService.BEAN_NAME)
	ErpCartAttrService erpCartAttrService;

	/**
	 * 获取购物车商品数量
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getCartShopNums(
			@Security
			String userId,
			@Security
			String sessionId,
			@Security
			String shopId){
		JSONObject jsonObject = new JSONObject();
		Map queryMap = new HashMap();
		try {
			if (userId==null && sessionId==null) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"用户代码或sessionId不能都为空");
			}
			if(userId!=null){
				queryMap.put("userId", userId);
			}
			if(sessionId!=null){
				queryMap.put("sessionId", sessionId);
			}
			
			/*if(shopId!=null){
				queryMap.put("shopId", shopId);
			}*/
			
			ErpCarts result = cartService.one(this.getStatementName("queryCartGoodsNum"),queryMap);
			
			jsonObject.put("nums", result.getNums()==null?0:result.getNums());
			jsonObject.put("prices", result.getPrice()==null?0:result.getPrice());
		} catch (Exception e) {
			e.printStackTrace();
			return executeRerutnFail(jsonObject);
		}
		if (!jsonObject.containsKey("nums")) {
			jsonObject.put("nums", 0);
		}
		return executeRerutn(jsonObject);
	}

	/**
	 * 获取购物车商品列表
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getCartShops(Map map){

		JSONObject jsonObject = new JSONObject();
		Map queryMap = new HashMap();

		if (map.get("userId")==null && map.get("sessionId")==null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户代码或sessionId不能都为空");
		}
		try {

			if(map.get("userId")!=null){
				queryMap.put("userId", map.get("userId"));
			}
			if(map.get("sessionId")!=null){
				queryMap.put("sessionId", map.get("sessionId"));	
			}
			/*if(map.get("shopId")!=null){
				queryMap.put("shopId", map.get("shopId"));	
			}*/
			List<ErpCarts> ErpCartslist = this.list(this.getStatementName("queryCartGoods"),queryMap);

			List data = new ArrayList();
			Map hmp = new HashMap();
			for(int i=0;i<ErpCartslist.size();i++){
				ErpCarts cart = ErpCartslist.get(i);
				String shopId = cart.getShopId();
				String shopName = cart.getShopName();
				String allowInCart = cart.getAllowInCart();
				String allowAddOrder = cart.getAllowAddOrder();
				String minAmount = String.valueOf(cart.getMinAmount());
				String logoUrl=cart.getLogoUrl();
				if(!hmp.containsKey(shopId)){
					Map shopGoods = new HashMap();
					shopGoods.put("shopId", shopId);
					shopGoods.put("shopName", shopName);
					shopGoods.put("logoUrl", logoUrl);
					shopGoods.put("allowInCart", allowInCart);
					shopGoods.put("allowAddOrder", allowAddOrder);
					if(!"1".equals(allowAddOrder)){
						shopGoods.put("notAddOrder", "此商家当前是非营业中状态");
					}
					shopGoods.put("minAmount", minAmount);
					shopGoods.put("price", new BigDecimal(cart.getPrice()*cart.getNums()).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
					List<ErpCarts> lists = new ArrayList<ErpCarts>();
					lists.add(cart);
					shopGoods.put("goods", lists);		
					data.add(shopGoods);
					hmp.put(shopId, shopGoods);
				}else{
					Map shopGoods = (Map) hmp.get(shopId);
					List<ErpCarts> lists = (List) shopGoods.get("goods");
					lists.add(cart);
					String sumPrice = null;
					if(shopGoods.get("price")!=null){
						for (int j = 0; j < lists.size(); j++) {
							sumPrice = String.valueOf(Double.parseDouble(shopGoods.get("price").toString())
									+ lists.get(j).getPrice()*lists.get(j).getNums());
						}
					}
					shopGoods.put("price", new BigDecimal(sumPrice).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
				}
			}
			jsonObject.put("data", data);

		} catch (Exception e) {
			e.printStackTrace();
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}

	/**
	 * 修改购物车商品数量
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject updateCartshopNum(Map map){
		if (map.get("cartId")==null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"购物车代码不能为空");
		}
		if (map.get("nums")==null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"商品数量不能为空");
		}
		JSONObject jsonObject = new JSONObject();
		Map updateMap = new HashMap();
		try {

			updateMap.put(ErpCart.COL_CART_ID, map.get("cartId"));
			ErpCarts updateErpCart = new ErpCarts();
			updateErpCart.setNums(Integer.parseInt(map.get("nums").toString()));
			updateMap.put("erpCart", updateErpCart);
			SqlUtis.prepareSql(updateMap, SqlUtis.getSQL(updateMap, ErpCart.COL_CART_ID,Types.VARCHAR,SqlUtis.EQ));
			if("0".equals(map.get("nums"))){
				cartService.delete(updateMap);
			}else{
				cartService.update(updateMap);
				ErpCart erpCart = cartService.one(updateMap);
				jsonObject.put("nums", erpCart.getNums());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}

	/**
	 * 删除购物车商品
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject deleteCartShops(Map map){
		if (map.get("cartId")==null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"购物车代码不能为空");
		}
		JSONObject jsonObject = new JSONObject();
		try {
			String[] cartId = map.get("cartId").toString().split(",");
			Map deleteMap = new HashMap();
			for (int i = 0; i < cartId.length; i++) {
				deleteMap.put(ErpCart.COL_CART_ID, cartId[i]);
				SqlUtis.prepareSql(deleteMap, SqlUtis.getSQL(deleteMap, ErpCart.COL_CART_ID,Types.VARCHAR,SqlUtis.EQ));
				cartService.delete(deleteMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}

	/**
	 * 把购物车临时商品转为用户商品
	 * @param userId
	 * @param sessionId
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public void changeTempGoodsToUser(
			@Security
			String userId, 
			@Security
			String sessionId) {
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(sessionId)) {
			return;
		}
		//查出购物车所有user_id商品(存在相同的商家代码，商品代码，需要合并到匿名购物车)，注意：立即购买的商品不需要合并！！！
		Map queryMap = new HashMap();
		queryMap.put(ErpCart.COL_USER_ID, userId);
		SqlUtis.prepareSql(queryMap
				, SqlUtis.getSQLRequired(queryMap, ErpCart.COL_USER_ID)
				," and a.type='0'"//不是立即购买的商品
				," and exists (select 1 from erp_cart b where (a.shop_id = b.shop_id and a.merchandise_id = b.merchandise_id) and b.session_id='"+sessionId+"' and b.user_id is null and b.type='0')"
				);
		List<ErpCart> carts =this.cartService.list(queryMap);//查查
		if (carts != null && carts.size()>0) {
			//把用户的购物车合并到匿名购物车
			for (ErpCart erpCart : carts) {
				Map updateMap = new HashMap();
				updateMap.put("nums", erpCart.getNums());
				updateMap.put("userId", userId);
				updateMap.put("sessionId", sessionId);
				updateMap.put("shopId", erpCart.getShopId());
				updateMap.put("merchandiseId", erpCart.getMerchandiseId());

				//先删除该商品
				Map deleteMap = new HashMap();
				deleteMap.put(ErpCart.COL_CART_ID, erpCart.getCartId());
				SqlUtis.prepareSql(deleteMap
						, SqlUtis.getSQLRequired(deleteMap, ErpCart.COL_CART_ID)
						);
				int result = this.cartService.delete(deleteMap);
				if (result != 1) {//合并
					throw new BusinessException("合并购物车失败");
				}
				//合并
				result = this.update(getStatementName("updateNumsCart"),updateMap);
				if (result != 1) {//合并
					throw new BusinessException("合并购物车失败");
				}
			}
		}
		//把未合并的匿名购物车商品更改user_id
		Map updateTempMap = new HashMap();
		updateTempMap.put("userId", userId);
		updateTempMap.put("sessionId", sessionId);
		this.update(getStatementName("updateTempCart"), updateTempMap);
	}
}
